package jys.test.yddata.utils;

import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.HashMap;
import java.util.Map;

public class PropertiesUtil extends Properties {
    private File userFile;
    private static Map<String, PropertiesUtil> propUtils = new HashMap<>();

    private PropertiesUtil(Context context, String iniName) throws IOException {
        super();

        userFile = new File(context.getFilesDir().getPath(), "user_"+iniName+".ini");
        if (userFile.exists())
            load(new InputStreamReader(
                    new FileInputStream(userFile),
                    StandardCharsets.UTF_8));
        else
            load(new InputStreamReader(
                    context.getAssets().open(iniName + ".ini"),
                    StandardCharsets.UTF_8));
    }

    public static PropertiesUtil buildFromDisk(Context context, String iniName) throws IOException {
        if (propUtils.containsKey(iniName))
            return propUtils.get(iniName);
        PropertiesUtil propUtil = new PropertiesUtil(context, iniName);
        propUtils.put(iniName, propUtil);
        return propUtil;
    }

    public void storeToUser() throws IOException {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(userFile);
            store(fileOutputStream, null);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean getBooleanProperty(String key) {
        return Boolean.parseBoolean(getProperty(key));
    }

    public int getIntProperty(String key) {
        return Integer.parseInt(getProperty(key));
    }

    public float getFloatProperty(String key) {
        return Float.parseFloat(getProperty(key));
    }

    public double getDoubleProperty(String key) {
        return Double.parseDouble(getProperty(key));
    }
}
